/*
 *
 *
 */

#include <string.h>
#include "user_card.h"

#if defined(GKT_CONFIG_RFID_ENABLE) && GKT_CONFIG_RFID_ENABLE

static __RETMEM_USR user_type_info_s s_user_card_info;

#define user_card_init	NULL
#define user_card_config	NULL

#define user_card_add_item	NULL
#define user_card_delete_item	NULL
#define user_card_reset_info	NULL
#define user_card_reset_partition	NULL

static const user_card_item_s *user_card_find_item(
				const uint8_t *data, uint32_t length)
{
	const user_card_item_s *c_item;
	uint32_t item_index;

	item_index = 0;
	while (item_index < g_user_card.instance.item_available_nums) {
		c_item = USER_CARD_ITEM(item_index);
		if (USER_ITEM_IS_USED(&c_item->header)
			&& ((uint32_t)c_item->data_length == length)
			&& !memcmp(c_item->data, data, length)) 
		{
			return c_item;
		}

		item_index++;
	}

	return NULL;
}

static int user_card_verify(uint32_t *user_id, 
				uint32_t excluded_user_index, uint32_t authority, 
				const uint8_t *data, uint32_t length)
{
	const user_card_item_s *c_item;

	gkt_unused(excluded_user_index);

	if ((length >= GKT_USER_CARD_ID_MINSIZE)
		&& (length <= GKT_USER_CARD_ID_MAXSIZE))
	{
		c_item = user_card_find_item(data, length);
		if (c_item) {
			if ((authority < GKT_USER_AUTH_TEMPORARY)
				&& ((uint32_t)c_item->header.authority.type != authority))
			{
				return GKT_USER_VERIFY_FAILED;
			}

			*user_id = GKT_USER_ID_BUILD(c_item->header.authority.type,
								c_item->header.authority.threaten,
								GKT_USER_TYPE_CARD, 
								c_item->header.user_index);
			return GKT_USER_VERIFY_PASSED;
		}
	}

	return GKT_USER_VERIFY_FAILED;
}
#define user_card_verify_update	NULL
#define user_card_verify_finalize	NULL

static int user_card_enroll_run(const uint8_t *data, 
				uint32_t length)
{
	const user_card_item_s *c_item;
	uint32_t i;
	int retval;

	if ((length >= GKT_USER_CARD_ID_MINSIZE)
		&& (length <= GKT_USER_CARD_ID_MAXSIZE)) 
	{
		c_item = user_card_find_item(data, length);
		if (!c_item) {
			for (i = 0; i < length; i++)
				g_user_card.enroll_item.data[i] = data[i];
			while (i < GKT_USER_CARD_ID_MAXSIZE)
				g_user_card.enroll_item.data[i++] = 0xff;
			g_user_card.enroll_item.data_length = length;
			retval = GKT_USER_ENROLL_COMPLETE;
		}
		else
			retval = GKT_USER_ENROLL_EXIST;
	}
	else
		retval = GKT_USER_ENROLL_UNSUPPORT;

	return retval;
}
#define user_card_enroll_init	NULL
#define user_card_enroll_uninit	NULL

USER_TYPE_OPS_DEFINE(card);
user_card_s g_user_card = {
	.instance = {
		.type = GKT_USER_TYPE_CARD,
		.flags = 0,
		.c_ops = USER_TYPE_OPS_PTR(card),
		.c_partition_name = "UserCard",
		.info = &s_user_card_info,
		.auth_user_maxnums = {
			GKT_USER_CARD_ADMIN_MAXNUMS,
			GKT_USER_CARD_NORMAL_MAXNUMS,
			GKT_USER_CARD_GUEST_MAXNUMS,
		},
		.item_size = USER_CARD_ITEM_SIZE,
		.item_data_maxsize = 0,
		.item_header = &g_user_card.enroll_item.header,
	}
};

#endif

